<template>
  <div class="container">
    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-input v-model="keyWord" style="width: 800px" placeholder="请输入客户姓名" :prefix-icon="Search"
        @keyup.enter="handleFilter" @input="handleInputChange" clearable />
      <el-button type="primary" @click="handleFilter" class="mx-5">搜索</el-button>

      <el-select v-model="filterForm.shop" placeholder="选择分店" style="width: 200px; margin-right: 20px"
        @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option 
          v-for="shop in shopLists"
          :key="shop.value"
          :label="shop.label"
          :value="shop.value"
        />
      </el-select>

      <el-select v-model="filterForm.customerType" placeholder="客户类型" style="width: 200px; margin-right: 20px"
        @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option label="包月" value="包月" />
        <el-option label="季度" value="季度" />
        <el-option label="年度" value="年度" />
      </el-select>
      <el-button type="success" @click="exportCurrentPage">导出当前页</el-button>
      <el-button type="success" @click="exportAllData">导出全部数据</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa' }">
      <el-table-column prop="list_index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="客户姓名" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column prop="address" label="客户地址" show-overflow-tooltip />
      <el-table-column prop="type" label="客户类型" width="100" />
      <el-table-column prop="shopName" label="所属分店" width="120">
        <template #default="{ row }">
          <assign-shop
            v-model:shopName="row.shopName"
            :memberId="row.index"
            type="member"
          />
        </template>
      </el-table-column>
      <el-table-column label="会员标签" width="180">
        <template #default="{ row }">
          <template v-if="row.tags?.length > 0">
            <el-tag v-for="(tag, index) in row.tags" :key="index" class="mr-2 mb-2" disable-transitions>
              {{ tag }}
            </el-tag>
          </template>
          <template v-else>
            无
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination background layout="total, sizes, prev, pager, next" :total="total" v-model:current-page="currentPage"
      v-model:page-size="pageSize" :page-sizes="[10, 20, 30]" @current-change="handlePageChange"
      @size-change="handleSizeChange" class="pagination-container" />
    <create-member></create-member>
  </div>
</template>

<script setup lang="ts" name="member">
import { reactive, ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import instance from '@/api'
import useExportExcel from '@/hooks/useExportExcel'
import CreateMember from '@/components/CreateMember.vue'
import { useStaffStore } from '@/stores/useStaffStore'
import { emitter } from '@/utils/emitter'
import AssignShop from '@/components/AssignShop.vue'

interface TableDataType {
  index: number
  list_index: number
  name: string
  phone: string
  address: string
  type: string
  shop: string
  shopName: string
  order_count: number
  tags: Array<string>
  contact_time: string
  due_time: string
}

interface PageData {
  total: number
  items: TableDataType[]
}

const keyWord = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const staffStore = useStaffStore()
const filterForm = reactive({
  shop: '',
  customerType: ''
})
const shopLists = computed(() => {
    return staffStore.shopList.map((shop: { id:number; shop_name: string }) => ({
        value: shop.id,
        label: shop.shop_name
    }))
})

const tableData = reactive<TableDataType[]>([])

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: keyWord.value.trim(),
      shop: filterForm.shop,
      type: filterForm.customerType
    }

    // 清除空参数
    const cleanedParams = Object.fromEntries(
      Object.entries(params).filter(([_, v]) => v !== '')
    )

    const resp = await instance.get<PageData>('/api/member/getMemberVip', {
      params: cleanedParams
    })
    if (resp.status === 200) {
      tableData.length = 0
      tableData.push(
        ...resp.data.items.map((item, index) => ({
          ...item,
          list_index: (currentPage.value - 1) * pageSize.value + index + 1,
          contact_time: item.contact_time || '',
          due_time: item.due_time || ''
        }))
      )
      total.value = resp.data.total
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 处理输入框变化
const handleInputChange = () => {
  if (keyWord.value === '') {
    handleFilter()
  }
}

// 筛选条件变化
const handleFilter = () => {
  currentPage.value = 1
  fetchData()
}

// 分页变化
const handlePageChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}

// 删除会员
const handleDelete = (row: TableDataType) => {
  ElMessageBox.confirm(
    `确定要删除会员 ${row.name} 吗？此操作不可恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const resp = await instance.delete(`/api/member/delete/${row.index}`)
      if (resp.status === 200) {
        ElMessage.success('删除成功')
        // 删除后重新加载当前页数据
        fetchData()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const { exportCurrentPage, exportAllData } = useExportExcel(tableData, keyWord, filterForm)

// 监听新增会员事件
const handleMemberAdded = (newMember: any) => {
  // 将新会员数据添加到tableData中
  tableData.push({
    ...newMember,
    list_index: tableData.length + 1
  })
  // 更新总数
  total.value += 1
}

onMounted(() => {
  fetchData()
  if(staffStore.shopList.length === 0) {
    staffStore.fetchShopList()
  }
  // 添加事件监听
  emitter.on('member-added', handleMemberAdded)
})

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  emitter.off('member-added', handleMemberAdded)
})
</script>

<style scoped>
.container {
  max-width: 100vw;
  padding: 20px;
  background: #fff;
}

.filter-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
}

.el-table--border {
  border: 1px solid #ebeef5;
}
</style>